<template>
  <div class="api-docs-layout">
    <aside class="api-docs-sidebar">
      <nav>
        <ul>
          <li :class="{active: activeSection==='quickstart'}"><a href="#quickstart" @click.prevent="scrollTo('quickstart')">快速开始</a></li>
          <li :class="{active: activeSection==='auth'}"><a href="#auth" @click.prevent="scrollTo('auth')">认证方式</a></li>
          
          <li class="nav-section-group">
            <div class="nav-section-title" @click="toggleSection('keys')">
              <span>API Key管理</span>
              <i :class="['fas', collapsedSections.keys ? 'fa-chevron-right' : 'fa-chevron-down']"></i>
            </div>
            <ul v-show="!collapsedSections.keys" class="nav-sub-list">
              <li :class="{active: activeSection==='key-list'}" class="nav-sub-item"><a href="#key-list" @click.prevent="scrollTo('key-list')">获取API Key列表</a></li>
              <li :class="{active: activeSection==='key-create'}" class="nav-sub-item"><a href="#key-create" @click.prevent="scrollTo('key-create')">创建API Key</a></li>
              <li :class="{active: activeSection==='key-delete'}" class="nav-sub-item"><a href="#key-delete" @click.prevent="scrollTo('key-delete')">删除API Key</a></li>
            </ul>
          </li>
          
          <li class="nav-section-group">
            <div class="nav-section-title" @click="toggleSection('chat')">
              <span>Chat Completions API</span>
              <i :class="['fas', collapsedSections.chat ? 'fa-chevron-right' : 'fa-chevron-down']"></i>
            </div>
            <ul v-show="!collapsedSections.chat" class="nav-sub-list">
              <li :class="{active: activeSection==='chat-completions'}" class="nav-sub-item"><a href="#chat-completions" @click.prevent="scrollTo('chat-completions')">创建对话完成</a></li>
              <li :class="{active: activeSection==='chat-stream'}" class="nav-sub-item"><a href="#chat-stream" @click.prevent="scrollTo('chat-stream')">流式响应</a></li>
              <li :class="{active: activeSection==='chat-params'}" class="nav-sub-item"><a href="#chat-params" @click.prevent="scrollTo('chat-params')">支持的参数</a></li>
            </ul>
          </li>
          
          <li class="nav-section-group">
            <div class="nav-section-title" @click="toggleSection('assistant')">
              <span>智能客服助手API</span>
              <i :class="['fas', collapsedSections.assistant ? 'fa-chevron-right' : 'fa-chevron-down']"></i>
            </div>
            <ul v-show="!collapsedSections.assistant" class="nav-sub-list">
              <li :class="{active: activeSection==='assistant-list'}" class="nav-sub-item"><a href="#assistant-list" @click.prevent="scrollTo('assistant-list')">获取智能客服列表</a></li>
              <li :class="{active: activeSection==='assistant-chat'}" class="nav-sub-item"><a href="#assistant-chat" @click.prevent="scrollTo('assistant-chat')">发送消息</a></li>
              <li :class="{active: activeSection==='assistant-history'}" class="nav-sub-item"><a href="#assistant-history" @click.prevent="scrollTo('assistant-history')">获取对话历史</a></li>
            </ul>
          </li>
          
          <li class="nav-section-group">
            <div class="nav-section-title" @click="toggleSection('kb')">
              <span>知识库API</span>
              <i :class="['fas', collapsedSections.kb ? 'fa-chevron-right' : 'fa-chevron-down']"></i>
            </div>
            <ul v-show="!collapsedSections.kb" class="nav-sub-list">
              <li :class="{active: activeSection==='kb-list'}" class="nav-sub-item"><a href="#kb-list" @click.prevent="scrollTo('kb-list')">获取知识库列表</a></li>
              <li :class="{active: activeSection==='kb-upload'}" class="nav-sub-item"><a href="#kb-upload" @click.prevent="scrollTo('kb-upload')">上传文档</a></li>
              <li :class="{active: activeSection==='kb-search'}" class="nav-sub-item"><a href="#kb-search" @click.prevent="scrollTo('kb-search')">搜索知识库</a></li>
            </ul>
          </li>
          
          <li :class="{active: activeSection==='models'}"><a href="#models" @click.prevent="scrollTo('models')">模型列表</a></li>
          <li :class="{active: activeSection==='error'}"><a href="#error" @click.prevent="scrollTo('error')">错误码</a></li>
          <li :class="{active: activeSection==='code'}"><a href="#code" @click.prevent="scrollTo('code')">示例代码</a></li>
        </ul>
      </nav>
    </aside>
    <main class="api-docs-main" ref="mainContent">
      <!-- 智能客服选择器 -->
      <div class="assistant-selector" v-if="assistants.length > 0">
        <el-card shadow="never" class="selector-card">
          <div class="selector-content">
            <label class="selector-label">选择智能客服：</label>
            <el-select 
              v-model="selectedAssistant" 
              placeholder="请选择一个智能客服"
              class="selector-dropdown"
              @change="handleAssistantChange"
            >
              <el-option
                v-for="assistant in assistants"
                :key="assistant.id"
                :label="assistant.name"
                :value="assistant.id"
              />
            </el-select>
            <div class="selector-info" v-if="selectedAssistantInfo">
              <span class="info-text">{{ selectedAssistantInfo.description || '暂无描述' }}</span>
            </div>
          </div>
        </el-card>
      </div>

      <section id="quickstart">
        <h1>店小二Agent API 文档</h1>
        <h2>快速开始</h2>
        <p>店小二Agent平台为开发者提供兼容 OpenAI 协议的 AI 对话能力、智能医疗助手、知识库管理等多种服务。</p>
        
        <div class="info-grid">
          <div class="info-item">
            <h4>API 基础URL</h4>
            <code>http://localhost:8080</code>
          </div>
          <div class="info-item">
            <h4>协议兼容</h4>
            <span>完全兼容 OpenAI GPT API 协议</span>
          </div>
          <div class="info-item">
            <h4>认证方式</h4>
            <span>API Key 认证</span>
          </div>
          <div class="info-item">
            <h4>数据格式</h4>
            <span>JSON</span>
          </div>
        </div>

        <h3>快速体验</h3>
        <div class="api-example">
          <div class="example-description">
            <p>使用你选择的智能客服进行对话：</p>
          </div>
          <pre class="code-block"><code>curl -X POST "http://localhost:8080/v1/chat/completions" \
  -H "Authorization: Bearer xz-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "dianxiaoer-v1",
    "messages": [
      {"role": "user", "content": "我最近总是头痛，可能是什么原因？"}
    ]{{selectedAssistant ? ',\n    "assistant_id": "' + selectedAssistant + '"' : ''}}
  }'</code></pre>
        </div>
      </section>

      <section id="auth">
        <h2>认证方式</h2>
        <p>店小二Agent平台使用 API Key 进行身份认证，所有接口调用都需要在 HTTP Header 中携带认证信息。</p>
        
        <div class="auth-steps">
          <h3>获取 API Key</h3>
          <ol>
            <li>登录店小二Agent平台</li>
            <li>进入 "API开放平台" → "API keys" 页面</li>
            <li>点击 "创建 API key" 按钮</li>
            <li>输入名称并创建，复制生成的 API Key</li>
          </ol>

          <h3>使用方式</h3>
          <p>在所有 API 请求的 Header 中包含：</p>
          <div class="code-example">
            <pre class="code-block"><code>Authorization: Bearer xz-your-api-key-here</code></pre>
          </div>

          <h3>安全提醒</h3>
          <div class="security-tips">
            <ul>
              <li>请妥善保存您的 API Key，不要在客户端代码中暴露</li>
              <li>建议定期轮换 API Key</li>
              <li>如发现 API Key 泄露，请立即删除并重新创建</li>
            </ul>
          </div>
        </div>
      </section>

      <section id="key">
        <h2>API Key管理</h2>
        <p>通过以下接口可以管理您的 API Keys。注意：这些接口需要使用 Web 登录认证，不是 API Key 认证。</p>

        <div class="api-endpoint" id="key-list">
          <h3>获取 API Key 列表</h3>
          <div class="endpoint-header">
            <span class="method get">GET</span>
            <span class="url">/api/keys</span>
          </div>
          
          <div class="endpoint-section">
            <h4>请求头</h4>
            <pre class="code-block"><code>Authorization: Bearer &lt;web-token&gt;</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>响应示例</h4>
            <pre class="code-block"><code>{
  "success": true,
  "data": [
    {
      "id": 1,
      "name": "我的API Key",
      "apiKey": "xz-abc***def",
      "status": "active",
      "usageCount": 156,
      "createTime": "2023-12-01T10:30:00Z",
      "lastUsedAt": "2023-12-15T14:22:33Z"
    }
  ],
  "message": "获取API Key列表成功"
}</code></pre>
          </div>
        </div>

        <div class="api-endpoint" id="key-create">
          <h3>创建 API Key</h3>
          <div class="endpoint-header">
            <span class="method post">POST</span>
            <span class="url">/api/keys</span>
          </div>
          
          <div class="endpoint-section">
            <h4>请求头</h4>
            <pre class="code-block"><code>Authorization: Bearer &lt;web-token&gt;
Content-Type: application/json</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>请求体</h4>
            <pre class="code-block"><code>{
  "name": "我的新API Key"
}</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>响应示例</h4>
            <pre class="code-block"><code>{
  "success": true,
  "data": {
    "id": 2,
    "name": "我的新API Key",
    "apiKey": "xz-1234567890abcdef1234567890abcdef123456",
    "status": "active",
    "usageCount": 0,
    "createTime": "2023-12-15T15:30:00Z"
  },
  "message": "API Key创建成功"
}</code></pre>
          </div>
        </div>

        <div class="api-endpoint" id="key-delete">
          <h3>删除 API Key</h3>
          <div class="endpoint-header">
            <span class="method delete">DELETE</span>
            <span class="url">/api/keys/{id}</span>
          </div>
          
          <div class="endpoint-section">
            <h4>请求头</h4>
            <pre class="code-block"><code>Authorization: Bearer &lt;web-token&gt;</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>响应示例</h4>
            <pre class="code-block"><code>{
  "success": true,
  "message": "API Key删除成功"
}</code></pre>
          </div>
        </div>
      </section>
      
      <section id="chat">
        <h2>Chat Completions API (兼容 OpenAI)</h2>
        <p>店小二Agent平台提供完全兼容 OpenAI GPT API 协议的对话接口，可以无缝替换 OpenAI API。</p>

        <div class="api-endpoint" id="chat-completions">
          <h3>创建对话完成</h3>
          <div class="endpoint-header">
            <span class="method post">POST</span>
            <span class="url">/v1/chat/completions</span>
          </div>
          
          <div class="endpoint-section">
            <h4>请求头</h4>
            <pre class="code-block"><code>Authorization: Bearer xz-your-api-key
Content-Type: application/json</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>请求体</h4>
            <pre class="code-block"><code>{
  "model": "dianxiaoer-v1",
  "messages": [
    {
      "role": "system",
      "content": "你是一个专业的客服助手，请提供准确、可靠的建议。"
    },
    {
      "role": "user", 
      "content": "你们的服务时间是怎样的？"
    }
  ],
  "max_tokens": 1000,
  "temperature": 0.7,
  "stream": false{{selectedAssistant ? ',\n  "assistant_id": "' + selectedAssistant + '"' : ''}}
}</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>响应示例</h4>
            <pre class="code-block"><code>{
  "id": "chatcmpl-123456789",
  "object": "chat.completion",
  "created": 1677652288,
  "model": "dianxiaoer-v1",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "头痛可能由多种原因引起，包括：\n\n1. 紧张性头痛：最常见的类型...\n2. 偏头痛：通常为一侧性搏动性疼痛...\n3. 生活方式因素：睡眠不足、压力、脱水...\n\n建议您记录头痛的频率、强度和触发因素，如果症状持续或加重，请及时就医。"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 45,
    "completion_tokens": 128,
    "total_tokens": 173
  }
}</code></pre>
          </div>
        </div>

        <div class="api-feature" id="chat-stream">
          <h3>流式响应</h3>
          <p>支持 Server-Sent Events (SSE) 流式响应，设置 <code>"stream": true</code>：</p>
          <pre class="code-block"><code>data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1677652288,"model":"dianxiaoer-v1","choices":[{"delta":{"content":"头痛"},"index":0,"finish_reason":null}]}

data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1677652288,"model":"dianxiaoer-v1","choices":[{"delta":{"content":"可能"},"index":0,"finish_reason":null}]}

data: [DONE]</code></pre>
        </div>

        <div class="params-table" id="chat-params">
          <h3>支持的参数</h3>
          <table>
            <thead>
              <tr>
                <th>参数</th>
                <th>类型</th>
                <th>必需</th>
                <th>说明</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td><code>model</code></td>
                <td>string</td>
                <td>是</td>
                <td>模型名称，目前支持 "dianxiaoer-v1"</td>
              </tr>
              <tr>
                <td><code>messages</code></td>
                <td>array</td>
                <td>是</td>
                <td>对话消息列表</td>
              </tr>
              <tr>
                <td><code>assistant_id</code></td>
                <td>string</td>
                <td>否</td>
                <td>指定使用的智能客服ID</td>
              </tr>
              <tr>
                <td><code>max_tokens</code></td>
                <td>integer</td>
                <td>否</td>
                <td>最大生成token数，默认1000</td>
              </tr>
              <tr>
                <td><code>temperature</code></td>
                <td>number</td>
                <td>否</td>
                <td>采样温度，0.0-2.0，默认0.7</td>
              </tr>
              <tr>
                <td><code>stream</code></td>
                <td>boolean</td>
                <td>否</td>
                <td>是否流式返回，默认false</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      <section id="assistant">
        <h2>智能助手API</h2>
        <p>针对店小二Agent平台定制的智能助手接口，集成了知识库和上下文记忆功能。</p>

        <div class="api-endpoint" id="assistant-list">
          <h3>获取智能客服列表</h3>
          <div class="endpoint-header">
            <span class="method get">GET</span>
            <span class="url">/api/assistants</span>
          </div>
          
          <div class="endpoint-section">
            <h4>请求头</h4>
            <pre class="code-block"><code>Authorization: Bearer xz-your-api-key</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>响应示例</h4>
            <pre class="code-block"><code>[
  {
    "id": 1,
    "name": "医疗咨询助手",
    "description": "专业的医疗咨询AI助手",
    "model": "dianxiaoer-v1",
    "systemPrompt": "你是一个专业的医疗助手...",
    "status": "active",
    "createTime": "2023-12-01T10:00:00Z"
  }
]</code></pre>
          </div>
        </div>

        <div class="api-endpoint" id="assistant-chat">
          <h3>发送消息</h3>
          <div class="endpoint-header">
            <span class="method post">POST</span>
            <span class="url">/api/assistants/chat</span>
          </div>
          
          <div class="endpoint-section">
            <h4>请求头</h4>
            <pre class="code-block"><code>Authorization: Bearer xz-your-api-key
Content-Type: application/json</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>请求体</h4>
            <pre class="code-block"><code>{
  "message": "我最近总是失眠，有什么好的建议吗？",
  "sessionId": "user-123-session-456",{{selectedAssistant ? '\n  "assistant_id": "' + selectedAssistant + '",' : ''}}
  "useKnowledgeBase": true,
  "memoryWindow": 10
}</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>响应示例</h4>
            <pre class="code-block"><code>{
  "success": true,
  "data": {
    "reply": "失眠是常见的睡眠障碍，根据医学知识库的信息...",
    "sessionId": "user-123-session-456",
    "messageId": "msg-789",
    "tokensUsed": 245,
    "knowledgeUsed": true
  },
  "message": "对话成功"
}</code></pre>
          </div>
        </div>

        <div class="api-endpoint" id="assistant-history">
          <h3>获取对话历史</h3>
          <div class="endpoint-header">
            <span class="method get">GET</span>
            <span class="url">/api/assistants/history</span>
          </div>
          
          <div class="endpoint-section">
            <h4>请求头</h4>
            <pre class="code-block"><code>Authorization: Bearer xz-your-api-key</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>查询参数</h4>
            <pre class="code-block"><code>sessionId=user-123-session-456&limit=50</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>响应示例</h4>
            <pre class="code-block"><code>{
  "success": true,
  "data": {
    "sessionId": "user-123-session-456",
    "messages": [
      {
        "id": "msg-001",
        "role": "user",
        "content": "我最近总是失眠",
        "timestamp": "2023-12-15T14:30:00Z"
      },
      {
        "id": "msg-002", 
        "role": "assistant",
        "content": "失眠可能由多种因素引起...",
        "timestamp": "2023-12-15T14:30:15Z"
      }
    ],
    "totalMessages": 2
  }
}</code></pre>
          </div>
        </div>
      </section>

      <section id="kb">
        <h2>知识库API</h2>
        <p>管理知识库文档，支持文档上传、搜索、统计等功能。</p>

        <div class="api-endpoint" id="kb-list">
          <h3>获取知识库列表</h3>
          <div class="endpoint-header">
            <span class="method get">GET</span>
            <span class="url">/api/knowledge/bases</span>
          </div>
          
          <div class="endpoint-section">
            <h4>请求头</h4>
            <pre class="code-block"><code>Authorization: Bearer xz-your-api-key</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>响应示例</h4>
            <pre class="code-block"><code>{
  "success": true,
  "data": [
    {
      "id": 1,
      "name": "内科医学知识库",
      "description": "包含内科常见疾病诊疗指南",
      "documentCount": 156,
      "createTime": "2023-12-01T10:00:00Z"
    }
  ]
}</code></pre>
          </div>
        </div>

        <div class="api-endpoint" id="kb-upload">
          <h3>上传文档</h3>
          <div class="endpoint-header">
            <span class="method post">POST</span>
            <span class="url">/api/knowledge/upload</span>
          </div>
          
          <div class="endpoint-section">
            <h4>请求头</h4>
            <pre class="code-block"><code>Authorization: Bearer xz-your-api-key
Content-Type: multipart/form-data</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>请求体 (FormData)</h4>
            <pre class="code-block"><code>file: [文件内容]
knowledgeBaseId: 1</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>响应示例</h4>
            <pre class="code-block"><code>{
  "success": true,
  "data": {
    "id": 123,
    "name": "糖尿病诊疗指南.pdf",
    "size": 2048576,
    "status": "processing",
    "uploadTime": "2023-12-15T15:30:00Z"
  },
  "message": "文档上传成功，正在处理中"
}</code></pre>
          </div>
        </div>

        <div class="api-endpoint" id="kb-search">
          <h3>搜索知识库</h3>
          <div class="endpoint-header">
            <span class="method post">POST</span>
            <span class="url">/api/knowledge/search</span>
          </div>
          
          <div class="endpoint-section">
            <h4>请求头</h4>
            <pre class="code-block"><code>Authorization: Bearer xz-your-api-key
Content-Type: application/json</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>请求体</h4>
            <pre class="code-block"><code>{
  "query": "糖尿病的症状有哪些",
  "maxResults": 10,
  "minScore": 0.7,
  "knowledgeBaseId": 1
}</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>响应示例</h4>
            <pre class="code-block"><code>{
  "success": true,
  "data": [
    {
      "content": "糖尿病的典型症状包括多饮、多尿、多食和体重减轻...",
      "source": "糖尿病诊疗指南.pdf",
      "score": 0.95,
      "documentId": 123
    }
  ]
}</code></pre>
          </div>
        </div>
      </section>

      <section id="models">
        <h2>模型列表</h2>
        <p>获取平台支持的AI模型信息，完全兼容 OpenAI Models API。</p>

        <div class="api-endpoint">
          <h3>列出可用模型</h3>
          <div class="endpoint-header">
            <span class="method get">GET</span>
            <span class="url">/v1/models</span>
          </div>
          
          <div class="endpoint-section">
            <h4>请求头</h4>
            <pre class="code-block"><code>Authorization: Bearer xz-your-api-key</code></pre>
          </div>

          <div class="endpoint-section">
            <h4>响应示例</h4>
            <pre class="code-block"><code>{
  "object": "list",
  "data": [
    {
      "id": "dianxiaoer-v1",
      "object": "model",
      "created": 1677610602,
      "owned_by": "dianxiaoer",
      "permission": [],
      "root": "dianxiaoer-v1",
      "parent": null
    }
  ]
}</code></pre>
          </div>
        </div>

        <div class="params-table">
          <h3>模型说明</h3>
          <table>
            <thead>
              <tr>
                <th>模型名称</th>
                <th>用途</th>
                <th>特点</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td><code>dianxiaoer-v1</code></td>
                <td>医疗咨询</td>
                <td>专业医疗知识，支持疾病诊断建议</td>
              </tr>
              <tr>
                <td><code>dianxiaoer-general-v1</code></td>
                <td>通用对话</td>
                <td>通用语言模型，适用于各种场景</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      <section id="error">
        <h2>错误码</h2>
        <p>店小二Agent平台使用标准HTTP状态码，同时提供详细的错误信息。</p>

        <div class="params-table">
          <h3>HTTP状态码</h3>
          <table>
            <thead>
              <tr>
                <th>状态码</th>
                <th>说明</th>
                <th>可能原因</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td><code>200</code></td>
                <td>请求成功</td>
                <td>-</td>
              </tr>
              <tr>
                <td><code>400</code></td>
                <td>请求参数错误</td>
                <td>参数格式不正确、缺少必需参数</td>
              </tr>
              <tr>
                <td><code>401</code></td>
                <td>未认证</td>
                <td>API Key 无效或已过期</td>
              </tr>
              <tr>
                <td><code>403</code></td>
                <td>权限不足</td>
                <td>无权访问该资源</td>
              </tr>
              <tr>
                <td><code>404</code></td>
                <td>资源不存在</td>
                <td>请求的资源未找到</td>
              </tr>
              <tr>
                <td><code>429</code></td>
                <td>请求过于频繁</td>
                <td>触发了速率限制</td>
              </tr>
              <tr>
                <td><code>500</code></td>
                <td>服务器内部错误</td>
                <td>服务器处理异常</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="api-feature">
          <h3>错误响应格式</h3>
          <pre class="code-block"><code>{
  "error": {
    "type": "invalid_request_error",
    "code": "invalid_api_key",
    "message": "Invalid API key provided",
    "param": null
  }
}</code></pre>
        </div>

        <div class="error-types">
          <h3>常见错误类型</h3>
          <ul>
            <li><code>invalid_request_error</code> - 请求格式错误</li>
            <li><code>authentication_error</code> - 认证失败</li>
            <li><code>permission_error</code> - 权限不足</li>
            <li><code>rate_limit_error</code> - 请求频率超限</li>
            <li><code>server_error</code> - 服务器错误</li>
          </ul>
        </div>
      </section>

      <section id="code">
        <h2>示例代码</h2>
        <p>以下是使用不同编程语言调用店小二Agent API的示例代码。</p>

        <div class="code-examples">
          <div class="code-example">
            <h3>Python (requests)</h3>
            <pre class="code-block"><code>import requests

# 使用 OpenAI 兼容接口
url = "http://localhost:8080/v1/chat/completions"
headers = {
    "Authorization": "Bearer xz-your-api-key",
    "Content-Type": "application/json"
}
data = {
    "model": "dianxiaoer-v1",
    "messages": [
        {"role": "user", "content": "我最近经常头痛，可能是什么原因？"}
    ],{{selectedAssistant ? '\n    "assistant_id": "' + selectedAssistant + '",' : ''}}
    "max_tokens": 1000,
    "temperature": 0.7
}

response = requests.post(url, headers=headers, json=data)
result = response.json()
print(result["choices"][0]["message"]["content"])</code></pre>
          </div>

          <div class="code-example">
            <h3>JavaScript (Node.js)</h3>
            <pre class="code-block"><code>const axios = require('axios');

async function chatWithXiaozhi() {
    try {
        const response = await axios.post(
            'http://localhost:8080/v1/chat/completions',
            {
                model: 'dianxiaoer-v1',
                messages: [
                    { role: 'user', content: '高血压的预防措施有哪些？' }
                ],{{selectedAssistant ? '\n                assistant_id: "' + selectedAssistant + '",' : ''}}
                max_tokens: 1000,
                temperature: 0.7
            },
            {
                headers: {
                    'Authorization': 'Bearer xz-your-api-key',
                    'Content-Type': 'application/json'
                }
            }
        );
        
        console.log(response.data.choices[0].message.content);
    } catch (error) {
        console.error('Error:', error.response?.data || error.message);
    }
}

chatWithXiaozhi();</code></pre>
          </div>

          <div class="code-example">
            <h3>cURL</h3>
            <pre class="code-block"><code># 基础对话请求
curl -X POST "http://localhost:8080/v1/chat/completions" \
  -H "Authorization: Bearer xz-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "dianxiaoer-v1",
    "messages": [
      {"role": "user", "content": "什么是糖尿病？"}
    ],{{selectedAssistant ? '\n    "assistant_id": "' + selectedAssistant + '",' : ''}}
    "max_tokens": 1000,
    "temperature": 0.7
  }'</code></pre>
          </div>
        </div>
      </section>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElSelect, ElOption, ElCard, ElMessage } from 'element-plus'
import axios from 'axios'

const mainContent = ref(null)
const activeSection = ref('quickstart')
const sectionIds = [
  'quickstart', 'auth', 
  'key-list', 'key-create', 'key-delete',
  'chat-completions', 'chat-stream', 'chat-params',
  'assistant-list', 'assistant-chat', 'assistant-history',
  'kb-list', 'kb-upload', 'kb-search',
  'models', 'error', 'code'
]

const assistants = ref([])
const selectedAssistant = ref('')

const collapsedSections = ref({
  keys: false,
  chat: false,
  assistant: false,
  kb: false
})

const selectedAssistantInfo = computed(() => {
  return assistants.value.find(a => a.id === selectedAssistant.value)
})

const toggleSection = (section) => {
  collapsedSections.value[section] = !collapsedSections.value[section]
}

const scrollTo = (id) => {
  const el = document.getElementById(id)
  if (el) {
    el.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }
}

const onScroll = () => {
  const scrollTop = mainContent.value.scrollTop
  let found = sectionIds[0]
  for (const id of sectionIds) {
    const el = document.getElementById(id)
    if (el && el.offsetTop - 80 <= scrollTop) {
      found = id
    }
  }
  activeSection.value = found
}

const handleAssistantChange = (value) => {
  selectedAssistant.value = value
  ElMessage.success(`已选择智能客服：${selectedAssistantInfo.value?.name}`)
}

const loadAssistants = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) return
    
    const response = await axios.get('/api/assistants', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    assistants.value = response.data || []
    
    // 如果有智能客服，默认选择第一个
    if (assistants.value.length > 0) {
      selectedAssistant.value = assistants.value[0].id
    }
  } catch (error) {
    console.error('获取智能客服列表失败:', error)
  }
}

onMounted(() => {
  mainContent.value.addEventListener('scroll', onScroll)
  loadAssistants()
})

onBeforeUnmount(() => {
  mainContent.value.removeEventListener('scroll', onScroll)
})
</script>

<style scoped>
.api-docs-layout {
  display: flex;
  min-height: 100vh;
  background: #f8fafc;
}

.api-docs-sidebar {
  width: 260px;
  background: #fff;
  border-right: 1px solid #e2e8f0;
  padding: 24px 0;
  position: sticky;
  top: 0;
  height: 100vh;
  overflow-y: auto;
}

.api-docs-sidebar nav ul {
  list-style: none;
  padding: 0 24px;
  margin: 0;
}

.api-docs-sidebar nav li {
  margin-bottom: 8px;
}

.api-docs-sidebar nav a {
  display: block;
  color: #64748b;
  text-decoration: none;
  font-size: 14px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.2s;
}

.api-docs-sidebar nav a:hover {
  background: #f1f5f9;
  color: #334155;
}

.api-docs-sidebar nav li.active a {
  background: #3b82f6;
  color: white;
  font-weight: 500;
}

.nav-section-group {
  margin: 16px 0;
}

.nav-section-group:first-child {
  margin-top: 8px;
}

.nav-section-title {
  color: #374151;
  font-weight: 600;
  font-size: 13px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  padding: 8px 12px;
  border-top: 1px solid #e2e8f0;
  padding-top: 16px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: all 0.2s;
  border-radius: 6px;
}

.nav-section-title:hover {
  background: #f8fafc;
}

.nav-section-group:first-child .nav-section-title {
  border-top: none;
  padding-top: 8px;
}

.nav-section-title i {
  font-size: 10px;
  transition: transform 0.2s;
}

.nav-sub-list {
  list-style: none;
  padding: 0;
  margin: 4px 0 0 0;
  overflow: hidden;
}

.nav-sub-item {
  margin: 0;
}

.nav-sub-item a {
  font-size: 13px;
  padding: 6px 12px 6px 28px;
  color: #6b7280;
  display: block;
  border-radius: 6px;
  margin: 2px 8px;
  transition: all 0.2s;
}

.nav-sub-item a:hover {
  background: #f1f5f9;
  color: #334155;
}

.nav-sub-item.active a {
  background: #3b82f6;
  color: white;
  font-weight: 500;
}

.api-docs-main {
  flex: 1;
  padding: 32px 48px;
  overflow-y: auto;
  max-height: 100vh;
  background: #fff;
}

.assistant-selector {
  margin-bottom: 32px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.selector-card {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
}

.selector-card :deep(.el-card__body) {
  padding: 16px 20px;
}

.selector-content {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.selector-label {
  font-weight: 500;
  color: #374151;
  white-space: nowrap;
}

.selector-dropdown {
  min-width: 200px;
}

.selector-info {
  flex: 1;
  min-width: 200px;
}

.info-text {
  color: #6b7280;
  font-size: 14px;
}

.api-docs-main h1 {
  font-size: 2.5rem;
  margin-bottom: 8px;
  color: #1e293b;
  font-weight: 700;
}

.api-docs-main h2 {
  font-size: 1.875rem;
  margin: 48px 0 24px 0;
  color: #3b82f6;
  font-weight: 600;
  border-bottom: 2px solid #e2e8f0;
  padding-bottom: 12px;
}

.api-docs-main h3 {
  font-size: 1.25rem;
  margin: 32px 0 16px 0;
  color: #374151;
  font-weight: 600;
}

.api-docs-main h4 {
  font-size: 1rem;
  margin: 20px 0 8px 0;
  color: #4b5563;
  font-weight: 600;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin: 24px 0;
}

.info-item {
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  border-left: 4px solid #3b82f6;
}

.info-item h4 {
  margin: 0 0 8px 0;
  color: #374151;
  font-size: 14px;
  font-weight: 600;
}

.info-item code {
  background: #e2e8f0;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 13px;
  color: #1e293b;
}

.api-endpoint {
  margin: 32px 0;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  overflow: hidden;
}

.api-endpoint h3 {
  margin: 0 0 16px 0;
  padding: 20px 20px 0 20px;
  color: #374151;
  font-size: 1.125rem;
  font-weight: 600;
}

.endpoint-header {
  background: #f8fafc;
  padding: 16px 20px;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.method {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.method.get {
  background: #dcfce7;
  color: #166534;
}

.method.post {
  background: #dbeafe;
  color: #1e40af;
}

.method.delete {
  background: #fee2e2;
  color: #dc2626;
}

.url {
  font-family: 'SF Mono', Monaco, monospace;
  font-size: 14px;
  color: #374151;
  font-weight: 500;
}

.endpoint-section {
  padding: 20px;
  border-bottom: 1px solid #f1f5f9;
}

.endpoint-section:last-child {
  border-bottom: none;
}

.code-block {
  background: #1e293b;
  color: #e2e8f0;
  border-radius: 8px;
  padding: 16px 20px;
  font-size: 14px;
  line-height: 1.5;
  overflow-x: auto;
  margin: 12px 0;
  font-family: 'SF Mono', Monaco, monospace;
}

.code-block code {
  background: none;
  color: inherit;
  padding: 0;
  border-radius: 0;
}

.api-feature {
  margin: 24px 0;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
  border-left: 4px solid #10b981;
}

.api-feature h3 {
  margin: 0 0 16px 0;
  color: #374151;
  font-size: 1.125rem;
  font-weight: 600;
}

.params-table {
  margin: 24px 0;
}

.params-table h3 {
  margin: 0 0 16px 0;
  color: #374151;
  font-size: 1.125rem;
  font-weight: 600;
}

.params-table table {
  width: 100%;
  border-collapse: collapse;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e2e8f0;
}

.params-table th {
  background: #f8fafc;
  padding: 12px 16px;
  text-align: left;
  font-weight: 600;
  color: #374151;
  border-bottom: 1px solid #e2e8f0;
}

.params-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #f1f5f9;
  vertical-align: top;
}

.params-table td code {
  background: #f1f5f9;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 13px;
  color: #1e293b;
}

.auth-steps, .security-tips {
  margin: 20px 0;
}

.auth-steps h3, .security-tips h3 {
  margin: 24px 0 12px 0;
  color: #374151;
  font-size: 1.125rem;
  font-weight: 600;
}

.security-tips ul {
  margin: 12px 0 0 20px;
  color: #6b7280;
}

.error-types ul {
  margin: 12px 0 0 20px;
  color: #6b7280;
}

.error-types h3 {
  margin: 24px 0 12px 0;
  color: #374151;
  font-size: 1.125rem;
  font-weight: 600;
}

.code-examples {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.code-example {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  overflow: hidden;
}

.code-example h3 {
  background: #f8fafc;
  margin: 0;
  padding: 16px 20px;
  border-bottom: 1px solid #e2e8f0;
  color: #374151;
  font-size: 1rem;
  font-weight: 600;
}

.code-example .code-block {
  margin: 0;
  border-radius: 0;
}

@media (max-width: 1024px) {
  .api-docs-layout {
    flex-direction: column;
  }
  
  .api-docs-sidebar {
    width: 100%;
    height: auto;
    position: static;
    border-right: none;
    border-bottom: 1px solid #e2e8f0;
  }
  
  .api-docs-main {
    padding: 24px;
  }
  
  .selector-content {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .selector-dropdown {
    width: 100%;
  }
}

@media (max-width: 640px) {
  .api-docs-main {
    padding: 16px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .endpoint-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

/* 统一所有内容区域h3标题的样式 */
.api-docs-main section > h3:not(.api-endpoint h3):not(.api-feature h3):not(.params-table h3) {
  margin: 32px 0 16px 0;
  color: #374151;
  font-size: 1.125rem;
  font-weight: 600;
}

/* 为内容区域添加更好的间距和排版 */
.api-docs-main p {
  line-height: 1.6;
  color: #4b5563;
  margin: 16px 0;
}

.api-docs-main ol, .api-docs-main ul:not(.nav-sub-list) {
  line-height: 1.6;
  color: #4b5563;
}

.api-docs-main ol li, .api-docs-main ul:not(.nav-sub-list) li {
  margin: 8px 0;
}

/* 优化代码块的边距 */
.api-docs-main .code-example pre {
  margin: 0;
}

/* 确保所有卡片和组件有一致的圆角 */
.api-endpoint, .api-feature, .params-table table {
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
}
</style>